package com.test.seataorder.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.seataorder.dao.OrderDao;
import com.test.seataorder.entity.Order;
import com.test.seataorder.feign.AccountFeignClient;
import com.test.seataorder.feign.StorageFeignClient;
import com.test.seataorder.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderDao, Order> implements OrderService {

    @Resource
    private AccountFeignClient accountFeignClient;

    @Resource
    private StorageFeignClient storageFeignClient;

    @Resource
    private OrderDao orderDao;

    /**
     * 开启分布式事务
     * 创建订单->调用库存服务扣减库存->调用账户服务扣减账户余额->修改订单状态
     */
    @GlobalTransactional
    public void create(Order order) {
        log.info("------->下单开始");
        // 本应用创建订单
        save(order);

        // 远程调用库存服务扣减库存
        log.info("------->seata-order-samples中扣减库存开始-------<");
        storageFeignClient.decrease(order.getProductId(), order.getCount());
        log.info("------->seata-order-samples中扣减库存结束-------<");

        // 远程调用账户服务扣减余额
        log.info("------->seata-order-samples中扣减余额开始-------<");
        accountFeignClient.decrease(order.getUserId(), order.getMoney());
        log.info("------->seata-order-samples中扣减余额结束-------<");

        // 修改订单状态为已完成
        log.info("------->seata-order-samples中修改订单状态开始-------<");

        orderDao.update(null, new UpdateWrapper<Order>()
                .lambda()
                .eq(Order::getUserId,order.getUserId())
                .set(Order::getStatus,1));
        log.info("------->seata-order-samples中修改订单状态结束-------<");

        log.info("------->下单结束");
    }
}
